home *** CD-ROM | disk | FTP | other *** search
/ Aminet 32 / Aminet 32 (1999)(Schatztruhe)[!][Aug 1999].iso / Aminet / dev / lang / Python151_Src.lha / Python1.5_Source / Modules / socketmodule.c < prev    next >
C/C++ Source or Header  |  1998-12-25  |  47KB  |  1,863 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Socket module */
  33.  
  34. /*
  35. This module provides an interface to Berkeley socket IPC.
  36.  
  37. Limitations:
  38.  
  39. - only AF_INET and AF_UNIX address families are supported
  40. - no read/write operations (use send/recv or makefile instead)
  41. - additional restrictions apply on Windows
  42.  
  43. Module interface:
  44.  
  45. - socket.error: exception raised for socket specific errors
  46. - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
  47. - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
  48. - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
  49. - socket.getprotobyname(protocolname) --> protocol number
  50. - socket.getservbyname(servicename, protocolname) --> port number
  51. - socket.socket(family, type [, proto]) --> new socket object
  52. - socket.ntohs(16 bit value) --> new int object
  53. - socket.ntohl(32 bit value) --> new int object
  54. - socket.htons(16 bit value) --> new int object
  55. - socket.htonl(32 bit value) --> new int object
  56. - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
  57. - an Internet socket address is a pair (hostname, port)
  58.   where hostname can be anything recognized by gethostbyname()
  59.   (including the dd.dd.dd.dd notation) and port is in host byte order
  60. - where a hostname is returned, the dd.dd.dd.dd notation is used
  61. - a UNIX domain socket address is a string specifying the pathname
  62.  
  63. Socket methods:
  64.  
  65. - s.accept() --> new socket object, sockaddr
  66. - s.bind(sockaddr) --> None
  67. - s.close() --> None
  68. - s.connect(sockaddr) --> None
  69. - s.connect_ex(sockaddr) --> 0 or errno (handy for e.g. async connect)
  70. - s.fileno() --> file descriptor
  71. - s.dup() --> same as socket.fromfd(os.dup(s.fileno(), ...)
  72. - s.getpeername() --> sockaddr
  73. - s.getsockname() --> sockaddr
  74. - s.getsockopt(level, optname[, buflen]) --> int or string
  75. - s.listen(backlog) --> None
  76. - s.makefile([mode[, bufsize]]) --> file object
  77. - s.recv(buflen [,flags]) --> string
  78. - s.recvfrom(buflen [,flags]) --> string, sockaddr
  79. - s.send(string [,flags]) --> nbytes
  80. - s.sendto(string, [flags,] sockaddr) --> nbytes
  81. - s.setblocking(0 | 1) --> None
  82. - s.setsockopt(level, optname, value) --> None
  83. - s.shutdown(how) --> None
  84. - repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>"
  85.  
  86. */
  87.  
  88. #include "Python.h"
  89. #if defined(WITH_THREAD) && !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
  90. #include "thread.h"
  91. #endif
  92.  
  93. #ifdef HAVE_UNISTD_H
  94. #include <unistd.h>
  95. #endif
  96.  
  97. #if !defined(MS_WINDOWS) && !defined(PYOS_OS2) && !defined(AMITCP)
  98. extern int gethostname(); /* For Solaris, at least */
  99. #endif
  100.  
  101. #if defined(PYCC_VACPP)
  102. #include <types.h>
  103. #include <io.h>
  104. #include <sys/ioctl.h>
  105. #include <utils.h>
  106. #include <ctype.h>
  107. #endif
  108.  
  109. #if defined(PYOS_OS2)
  110. #define  INCL_DOS
  111. #define  INCL_DOSERRORS
  112. #define  INCL_NOPMAPI
  113. #include <os2.h>
  114. #endif
  115.  
  116. #include <sys/types.h>
  117. #include "mytime.h"
  118.  
  119. #include <signal.h>
  120. #ifndef MS_WINDOWS
  121. #include <netdb.h>
  122. #include <sys/socket.h>
  123. #include <netinet/in.h>
  124. #include <fcntl.h>
  125. #else
  126. #include <winsock.h>
  127. #include <fcntl.h>
  128. #endif
  129. #if defined(AMITCP) || defined(INET225)
  130. #define SYS_TTYCHARS_H
  131. #include <sys/ioctl.h>
  132. #include <proto/socket.h>
  133. #endif
  134. #ifdef HAVE_SYS_UN_H
  135. #include <sys/un.h>
  136. #else
  137. #undef AF_UNIX
  138. #endif
  139.  
  140. #ifndef O_NDELAY
  141. #define O_NDELAY O_NONBLOCK    /* For QNX only? */
  142. #endif
  143.  
  144. #ifdef USE_GUSI
  145. /* fdopen() isn't declared in stdio.h (sigh) */
  146. #include <GUSI.h>
  147. #endif
  148.  
  149.  
  150. /* Here we have some hacks to choose between K&R or ANSI style function
  151.    definitions.  For NT to build this as an extension module (ie, DLL)
  152.    it must be compiled by the C++ compiler, as it takes the address of
  153.    a static data item exported from the main Python DLL.
  154. */
  155. #ifdef MS_WINDOWS
  156. /* seem to be a few differences in the API */
  157. #define close closesocket
  158. #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
  159. #define FORCE_ANSI_FUNC_DEFS
  160. #endif
  161.  
  162. #if defined(PYOS_OS2)
  163. #define close soclose
  164. #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
  165. #define FORCE_ANSI_FUNC_DEFS
  166. #endif
  167.  
  168. #ifdef AMITCP
  169. /* seem to be a few differences in the API */
  170. //#define close CloseSocket
  171. #define ioctlsocket IoctlSocket
  172. #undef NO_DUP
  173. #undef AF_UNIX
  174. #define FORCE_ANSI_FUNC_DEFS
  175. #endif
  176.  
  177. #ifdef INET225
  178. /* seem to be a few differences in the API */
  179. #define close s_close
  180. #define ioctlsocket s_ioctl
  181. #undef NO_DUP
  182. static __inline int dup(int oldsd) { return s_dup(oldsd); }
  183. #undef AF_UNIX
  184. #define FORCE_ANSI_FUNC_DEFS
  185. #endif
  186.  
  187. #ifdef FORCE_ANSI_FUNC_DEFS
  188. #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name )    \
  189. fnname( arg1type arg1name )
  190.  
  191. #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
  192. fnname( arg1type arg1name, arg2type arg2name )
  193.  
  194. #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name )    \
  195. fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name )
  196.  
  197. #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name, arg4type, arg4name )    \
  198. fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name, arg4type arg4name )
  199.  
  200. #else /* !FORCE_ANSI_FN_DEFS */
  201. #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name )    \
  202. fnname( arg1name )    \
  203.     arg1type arg1name;
  204.  
  205. #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
  206. fnname( arg1name, arg2name )    \
  207.     arg1type arg1name;    \
  208.     arg2type arg2name;
  209.  
  210. #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name ) \
  211. fnname( arg1name, arg2name, arg3name )    \
  212.     arg1type arg1name;    \
  213.     arg2type arg2name;    \
  214.     arg3type arg3name;
  215.  
  216. #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name, arg4type, arg4name ) \
  217. fnname( arg1name, arg2name, arg3name, arg4name )    \
  218.     arg1type arg1name;    \
  219.     arg2type arg2name;    \
  220.     arg3type arg3name;    \
  221.     arg4type arg4name;
  222.  
  223. #endif /* !FORCE_ANSI_FN_DEFS */
  224.  
  225. /* Global variable holding the exception type for errors detected
  226.    by this module (but not argument type or memory errors, etc.). */
  227.  
  228. static PyObject *PySocket_Error;
  229.  
  230.  
  231. /* Convenience function to raise an error according to errno
  232.    and return a NULL pointer from a function. */
  233.  
  234. static PyObject *
  235. PySocket_Err Py_PROTO((void))
  236. {
  237. #ifdef MS_WINDOWS
  238.     if (WSAGetLastError()) {
  239.         PyObject *v;
  240.         v = Py_BuildValue("(is)", WSAGetLastError(), "winsock error");
  241.         if (v != NULL) {
  242.             PyErr_SetObject(PySocket_Error, v);
  243.             Py_DECREF(v);
  244.         }
  245.         return NULL;
  246.     }
  247.     else
  248. #endif
  249.  
  250. #if defined(PYOS_OS2)
  251.     if (sock_errno() != NO_ERROR) {
  252.         APIRET rc;
  253.         ULONG  msglen;
  254.         char   outbuf[100];
  255.         int    myerrorcode = sock_errno();
  256.  
  257.         /* Retrieve Socket-Related Error Message from MPTN.MSG File */
  258.         rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
  259.                            myerrorcode - SOCBASEERR + 26, "mptn.msg", &msglen);
  260.         if (rc == NO_ERROR) {
  261.             PyObject *v;
  262.  
  263.             outbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
  264.             if (strlen(outbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */
  265.                 char *lastc = &outbuf[ strlen(outbuf)-1 ];
  266.                 while (lastc > outbuf && isspace(*lastc))
  267.                     *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
  268.             }
  269.             v = Py_BuildValue("(is)", myerrorcode, outbuf);
  270.             if (v != NULL) {
  271.                 PyErr_SetObject(PySocket_Error, v);
  272.                 Py_DECREF(v);
  273.             }
  274.             return NULL;
  275.         }
  276.     }
  277. #endif
  278.  
  279.     return PyErr_SetFromErrno(PySocket_Error);
  280. }
  281.  
  282.  
  283. /* The object holding a socket.  It holds some extra information,
  284.    like the address family, which is used to decode socket address
  285.    arguments properly. */
  286.  
  287. typedef struct {
  288.     PyObject_HEAD
  289.     int sock_fd;        /* Socket file descriptor */
  290.     int sock_family;    /* Address family, e.g., AF_INET */
  291.     int sock_type;        /* Socket type, e.g., SOCK_STREAM */
  292.     int sock_proto;        /* Protocol type, usually 0 */
  293.     union sock_addr {
  294.         struct sockaddr_in in;
  295. #ifdef AF_UNIX
  296.         struct sockaddr_un un;
  297. #endif
  298.     } sock_addr;
  299. } PySocketSockObject;
  300.  
  301.  
  302. /* A forward reference to the Socktype type object.
  303.    The Socktype variable contains pointers to various functions,
  304.    some of which call newsockobject(), which uses Socktype, so
  305.    there has to be a circular reference. */
  306.  
  307. staticforward PyTypeObject PySocketSock_Type;
  308.  
  309.  
  310. /* Create a new socket object.
  311.    This just creates the object and initializes it.
  312.    If the creation fails, return NULL and set an exception (implicit
  313.    in NEWOBJ()). */
  314.  
  315. static PySocketSockObject *
  316. BUILD_FUNC_DEF_4(PySocketSock_New,int,fd, int,family, int,type, int,proto)
  317. {
  318.     PySocketSockObject *s;
  319.     PySocketSock_Type.ob_type = &PyType_Type;
  320.     s = PyObject_NEW(PySocketSockObject, &PySocketSock_Type);
  321.     if (s != NULL) {
  322.         s->sock_fd = fd;
  323.         s->sock_family = family;
  324.         s->sock_type = type;
  325.         s->sock_proto = proto;
  326. #ifdef AMITCP
  327.         /* XXX lines added for AMITCP by I.J. 15-dec-96 */
  328.         /* (AMITCP seems to want a zeroed out sock_addr structure) */
  329.         memset(&s->sock_addr, 0, sizeof(s->sock_addr));
  330.         if(family==AF_INET) s->sock_addr.in.sin_len=sizeof(struct sockaddr_in);
  331. #ifdef AF_UNIX
  332.         if(family==AF_UNIX) s->sock_addr.un.sun_len=sizeof(struct sockaddr_un);
  333. #endif
  334. #endif /* AMITCP */
  335.     }
  336.     return s;
  337. }
  338.  
  339.  
  340. /* Lock to allow python interpreter to continue, but only allow one 
  341.    thread to be in gethostbyname */
  342. #if defined(WITH_THREAD) && !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
  343. type_lock gethostbyname_lock;
  344. #endif
  345.  
  346.  
  347. /* Convert a string specifying a host name or one of a few symbolic
  348.    names to a numeric IP address.  This usually calls gethostbyname()
  349.    to do the work; the names "" and "<broadcast>" are special.
  350.    Return the length (should always be 4 bytes), or negative if
  351.    an error occurred; then an exception is raised. */
  352.  
  353. static int
  354. BUILD_FUNC_DEF_2(setipaddr, char*,name, struct sockaddr_in *,addr_ret)
  355. {
  356.     struct hostent *hp;
  357.     int d1, d2, d3, d4;
  358.     char ch;
  359. #ifdef HAVE_GETHOSTBYNAME_R
  360.     struct hostent hp_allocated;
  361.     char buf[1001];
  362.     int buf_len = (sizeof buf) - 1;
  363.     int errnop;
  364. #endif /* HAVE_GETHOSTBYNAME_R */
  365.  
  366.     memset((void *) addr_ret, '\0', sizeof(*addr_ret));
  367.     if (name[0] == '\0') {
  368.         addr_ret->sin_addr.s_addr = INADDR_ANY;
  369.         return 4;
  370.     }
  371.     if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
  372.         addr_ret->sin_addr.s_addr = INADDR_BROADCAST;
  373.         return 4;
  374.     }
  375.     if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
  376.         0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
  377.         0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
  378.         addr_ret->sin_addr.s_addr = htonl(
  379.             ((long) d1 << 24) | ((long) d2 << 16) |
  380.             ((long) d3 << 8) | ((long) d4 << 0));
  381.         return 4;
  382.     }
  383.     Py_BEGIN_ALLOW_THREADS
  384. #ifdef HAVE_GETHOSTBYNAME_R
  385.     hp = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  386. #else /* not HAVE_GETHOSTBYNAME_R */
  387. #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
  388.     acquire_lock(gethostbyname_lock,1);
  389. #endif
  390.     hp = gethostbyname(name);
  391. #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
  392.     release_lock(gethostbyname_lock);
  393. #endif
  394. #endif /* HAVE_GETHOSTBYNAME_R */
  395.     Py_END_ALLOW_THREADS
  396.  
  397.     if (hp == NULL) {
  398. #ifdef HAVE_HSTRERROR
  399.             /* Let's get real error message to return */
  400.             extern int h_errno;
  401.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  402. #else
  403.         PyErr_SetString(PySocket_Error, "host not found");
  404. #endif
  405.         return -1;
  406.     }
  407.     memcpy((char *) &addr_ret->sin_addr, hp->h_addr, hp->h_length);
  408.     return hp->h_length;
  409. }
  410.  
  411.  
  412. /* Create a string object representing an IP address.
  413.    This is always a string of the form 'dd.dd.dd.dd' (with variable
  414.    size numbers). */
  415.  
  416. static PyObject *
  417. BUILD_FUNC_DEF_1(makeipaddr, struct sockaddr_in *,addr)
  418. {
  419.     long x = ntohl(addr->sin_addr.s_addr);
  420.     char buf[100];
  421.     sprintf(buf, "%d.%d.%d.%d",
  422.         (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
  423.         (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff);
  424.     return PyString_FromString(buf);
  425. }
  426.  
  427.  
  428. /* Create an object representing the given socket address,
  429.    suitable for passing it back to bind(), connect() etc.
  430.    The family field of the sockaddr structure is inspected
  431.    to determine what kind of address it really is. */
  432.  
  433. /*ARGSUSED*/
  434. static PyObject *
  435. BUILD_FUNC_DEF_2(makesockaddr,struct sockaddr *,addr, int,addrlen)
  436. {
  437.     if (addrlen == 0) {
  438.         /* No address -- may be recvfrom() from known socket */
  439.         Py_INCREF(Py_None);
  440.         return Py_None;
  441.     }
  442.  
  443.     switch (addr->sa_family) {
  444.  
  445.     case AF_INET:
  446.     {
  447.         struct sockaddr_in *a = (struct sockaddr_in *) addr;
  448.         PyObject *addrobj = makeipaddr(a);
  449.         PyObject *ret = NULL;
  450.         if (addrobj) {
  451.             ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
  452.             Py_DECREF(addrobj);
  453.         }
  454.         return ret;
  455.     }
  456.  
  457. #ifdef AF_UNIX
  458.     case AF_UNIX:
  459.     {
  460.         struct sockaddr_un *a = (struct sockaddr_un *) addr;
  461.         return PyString_FromString(a->sun_path);
  462.     }
  463. #endif /* AF_UNIX */
  464.  
  465.     /* More cases here... */
  466.  
  467.     default:
  468.         /* If we don't know the address family, don't raise an
  469.            exception -- return it as a tuple. */
  470.         return Py_BuildValue("is#",
  471.                      addr->sa_family,
  472.                      addr->sa_data,
  473.                      sizeof(addr->sa_data));
  474.  
  475.     }
  476. }
  477.  
  478.  
  479. /* Parse a socket address argument according to the socket object's
  480.    address family.  Return 1 if the address was in the proper format,
  481.    0 of not.  The address is returned through addr_ret, its length
  482.    through len_ret. */
  483.  
  484. static int
  485. BUILD_FUNC_DEF_4(
  486. getsockaddrarg,PySocketSockObject *,s, PyObject *,args, struct sockaddr **,addr_ret, int *,len_ret)
  487. {
  488.     switch (s->sock_family) {
  489.  
  490. #ifdef AF_UNIX
  491.     case AF_UNIX:
  492.     {
  493.         struct sockaddr_un* addr;
  494.         char *path;
  495.         int len;
  496.         addr = (struct sockaddr_un* )&(s->sock_addr).un;
  497.         if (!PyArg_Parse(args, "s#", &path, &len))
  498.             return 0;
  499.         if (len > sizeof addr->sun_path) {
  500.             PyErr_SetString(PySocket_Error,
  501.                     "AF_UNIX path too long");
  502.             return 0;
  503.         }
  504.         addr->sun_family = AF_UNIX;
  505.         memcpy(addr->sun_path, path, len);
  506.         addr->sun_path[len] = 0;
  507.         *addr_ret = (struct sockaddr *) addr;
  508.         *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
  509.         return 1;
  510.     }
  511. #endif /* AF_UNIX */
  512.  
  513.     case AF_INET:
  514.     {
  515.         struct sockaddr_in* addr;
  516.         char *host;
  517.         int port;
  518.          addr=(struct sockaddr_in*)&(s->sock_addr).in;
  519.         if (!PyArg_Parse(args, "(si)", &host, &port))
  520.             return 0;
  521.         if (setipaddr(host, addr) < 0)
  522.             return 0;
  523.         addr->sin_family = AF_INET;
  524.         addr->sin_port = htons((short)port);
  525.         *addr_ret = (struct sockaddr *) addr;
  526.         *len_ret = sizeof *addr;
  527.         return 1;
  528.     }
  529.  
  530.     /* More cases here... */
  531.  
  532.     default:
  533.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  534.         return 0;
  535.  
  536.     }
  537. }
  538.  
  539.  
  540. /* Get the address length according to the socket object's address family. 
  541.    Return 1 if the family is known, 0 otherwise.  The length is returned
  542.    through len_ret. */
  543.  
  544. static int
  545. BUILD_FUNC_DEF_2(getsockaddrlen,PySocketSockObject *,s, int *,len_ret)
  546. {
  547.     switch (s->sock_family) {
  548.  
  549. #ifdef AF_UNIX
  550.     case AF_UNIX:
  551.     {
  552.         *len_ret = sizeof (struct sockaddr_un);
  553.         return 1;
  554.     }
  555. #endif /* AF_UNIX */
  556.  
  557.     case AF_INET:
  558.     {
  559.         *len_ret = sizeof (struct sockaddr_in);
  560.         return 1;
  561.     }
  562.  
  563.     /* More cases here... */
  564.  
  565.     default:
  566.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  567.         return 0;
  568.  
  569.     }
  570. }
  571.  
  572.  
  573. /* s.accept() method */
  574.  
  575. static PyObject *
  576. BUILD_FUNC_DEF_2(PySocketSock_accept,PySocketSockObject *,s, PyObject *,args)
  577. {
  578.     char addrbuf[256];
  579.     int addrlen, newfd;
  580.     PyObject *sock = NULL;
  581.     PyObject *addr = NULL;
  582.     PyObject *res = NULL;
  583.  
  584.     if (!PyArg_NoArgs(args))
  585.         return NULL;
  586.     if (!getsockaddrlen(s, &addrlen))
  587.         return NULL;
  588.     Py_BEGIN_ALLOW_THREADS
  589.     newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  590.     Py_END_ALLOW_THREADS
  591.     if (newfd < 0)
  592.         return PySocket_Err();
  593.  
  594.     /* Create the new object with unspecified family,
  595.        to avoid calls to bind() etc. on it. */
  596.     sock = (PyObject *) PySocketSock_New(newfd,
  597.                     s->sock_family,
  598.                     s->sock_type,
  599.                     s->sock_proto);
  600.     if (sock == NULL) {
  601.         close(newfd);
  602.         goto finally;
  603.     }
  604.     if (!(addr = makesockaddr((struct sockaddr *) addrbuf, addrlen)))
  605.         goto finally;
  606.  
  607.     if (!(res = Py_BuildValue("OO", sock, addr)))
  608.         goto finally;
  609.  
  610.   finally:
  611.     Py_XDECREF(sock);
  612.     Py_XDECREF(addr);
  613.     return res;
  614. }
  615.  
  616.  
  617. /* s.setblocking(1 | 0) method */
  618.  
  619. static PyObject *
  620. BUILD_FUNC_DEF_2(PySocketSock_setblocking,PySocketSockObject*,s,PyObject*,args)
  621. {
  622.     int block;
  623. #ifndef MS_WINDOWS
  624.     int delay_flag;
  625. #endif
  626.     if (!PyArg_Parse(args, "i", &block))
  627.         return NULL;
  628.     Py_BEGIN_ALLOW_THREADS
  629. #ifndef MS_WINDOWS
  630. #ifdef PYOS_OS2
  631.     block = !block;
  632.     ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
  633. #else /* !PYOS_OS2 */
  634.  #if defined(AMITCP) || defined (INET225)
  635.     block = !block;
  636.     ioctlsocket(s->sock_fd, FIONBIO, &block);
  637.  #else
  638.     delay_flag = fcntl (s->sock_fd, F_GETFL, 0);
  639.     if (block)
  640.         delay_flag &= (~O_NDELAY);
  641.     else
  642.         delay_flag |= O_NDELAY;
  643.     fcntl (s->sock_fd, F_SETFL, delay_flag);
  644. #endif /* !AMITCP || INET225 */
  645. #endif /* !PYOS_OS2 */
  646. #else /* MS_WINDOWS */
  647.     block = !block;
  648.     ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
  649. #endif /* MS_WINDOWS */
  650.     Py_END_ALLOW_THREADS
  651.  
  652.     Py_INCREF(Py_None);
  653.     return Py_None;
  654. }
  655.  
  656.  
  657. /* s.setsockopt() method.
  658.    With an integer third argument, sets an integer option.
  659.    With a string third argument, sets an option from a buffer;
  660.    use optional built-in module 'struct' to encode the string. */
  661.  
  662. static PyObject *
  663. BUILD_FUNC_DEF_2(PySocketSock_setsockopt,PySocketSockObject *,s, PyObject *,args)
  664. {
  665.     int level;
  666.     int optname;
  667.     int res;
  668.     char *buf;
  669.     int buflen;
  670.     int flag;
  671.  
  672.     if (PyArg_Parse(args, "(iii)", &level, &optname, &flag)) {
  673.         buf = (char *) &flag;
  674.         buflen = sizeof flag;
  675.     }
  676.     else {
  677.         PyErr_Clear();
  678.         if (!PyArg_Parse(args, "(iis#)", &level, &optname,
  679.                  &buf, &buflen))
  680.             return NULL;
  681.     }
  682.     res = setsockopt(s->sock_fd, level, optname, (ANY *)buf, buflen);
  683.     if (res < 0)
  684.         return PySocket_Err();
  685.     Py_INCREF(Py_None);
  686.     return Py_None;
  687. }
  688.  
  689.  
  690. /* s.getsockopt() method.
  691.    With two arguments, retrieves an integer option.
  692.    With a third integer argument, retrieves a string buffer of that size;
  693.    use optional built-in module 'struct' to decode the string. */
  694.  
  695. static PyObject *
  696. BUILD_FUNC_DEF_2(PySocketSock_getsockopt,PySocketSockObject *,s, PyObject *,args)
  697. {
  698.     int level;
  699.     int optname;
  700.     int res;
  701.     PyObject *buf;
  702.     int buflen = 0;
  703.  
  704.     if (!PyArg_ParseTuple(args, "ii|i", &level, &optname, &buflen))
  705.         return NULL;
  706.     
  707.     if (buflen == 0) {
  708.         int flag = 0;
  709.         int flagsize = sizeof flag;
  710.         res = getsockopt(s->sock_fd, level, optname,
  711.                  (ANY *)&flag, &flagsize);
  712.         if (res < 0)
  713.             return PySocket_Err();
  714.         return PyInt_FromLong(flag);
  715.     }
  716.     if (buflen <= 0 || buflen > 1024) {
  717.         PyErr_SetString(PySocket_Error,
  718.                 "getsockopt buflen out of range");
  719.         return NULL;
  720.     }
  721.     buf = PyString_FromStringAndSize((char *)NULL, buflen);
  722.     if (buf == NULL)
  723.         return NULL;
  724.     res = getsockopt(s->sock_fd, level, optname,
  725.              (ANY *)PyString_AsString(buf), &buflen);
  726.     if (res < 0) {
  727.         Py_DECREF(buf);
  728.         return PySocket_Err();
  729.     }
  730.     _PyString_Resize(&buf, buflen);
  731.     return buf;
  732. }
  733.  
  734.  
  735. /* s.bind(sockaddr) method */
  736.  
  737. static PyObject *
  738. BUILD_FUNC_DEF_2(PySocketSock_bind,PySocketSockObject *,s, PyObject *,args)
  739. {
  740.     struct sockaddr *addr;
  741.     int addrlen;
  742.     int res;
  743.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  744.         return NULL;
  745.     Py_BEGIN_ALLOW_THREADS
  746.     res = bind(s->sock_fd, addr, addrlen);
  747.     Py_END_ALLOW_THREADS
  748.     if (res < 0)
  749.         return PySocket_Err();
  750.     Py_INCREF(Py_None);
  751.     return Py_None;
  752. }
  753.  
  754.  
  755. /* s.close() method.
  756.    Set the file descriptor to -1 so operations tried subsequently
  757.    will surely fail. */
  758.  
  759. static PyObject *
  760. BUILD_FUNC_DEF_2(PySocketSock_close,PySocketSockObject *,s, PyObject *,args)
  761. {
  762.     if (!PyArg_NoArgs(args))
  763.         return NULL;
  764.     if (s->sock_fd != -1) {
  765.         Py_BEGIN_ALLOW_THREADS
  766.         (void) close(s->sock_fd);
  767.         Py_END_ALLOW_THREADS
  768.     }
  769.     s->sock_fd = -1;
  770.     Py_INCREF(Py_None);
  771.     return Py_None;
  772. }
  773.  
  774.  
  775. /* s.connect(sockaddr) method */
  776.  
  777. static PyObject *
  778. BUILD_FUNC_DEF_2(PySocketSock_connect,PySocketSockObject *,s, PyObject *,args)
  779. {
  780.     struct sockaddr *addr;
  781.     int addrlen;
  782.     int res;
  783.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  784.         return NULL;
  785.     Py_BEGIN_ALLOW_THREADS
  786.     res = connect(s->sock_fd, addr, addrlen);
  787.     Py_END_ALLOW_THREADS
  788.     if (res < 0)
  789.         return PySocket_Err();
  790.     Py_INCREF(Py_None);
  791.     return Py_None;
  792. }
  793.  
  794.  
  795. /* s.connect_ex(sockaddr) method */
  796.  
  797. static PyObject *
  798. BUILD_FUNC_DEF_2(PySocketSock_connect_ex,PySocketSockObject *,s, PyObject *,args)
  799. {
  800.     struct sockaddr *addr;
  801.     int addrlen;
  802.     int res;
  803.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  804.         return NULL;
  805.     Py_BEGIN_ALLOW_THREADS
  806.     res = connect(s->sock_fd, addr, addrlen);
  807.     Py_END_ALLOW_THREADS
  808.     if (res != 0)
  809.         res = errno;
  810.     return PyInt_FromLong((long) res);
  811. }
  812.  
  813.  
  814. /* s.fileno() method */
  815.  
  816. static PyObject *
  817. BUILD_FUNC_DEF_2(PySocketSock_fileno,PySocketSockObject *,s, PyObject *,args)
  818. {
  819.     if (!PyArg_NoArgs(args))
  820.         return NULL;
  821.     return PyInt_FromLong((long) s->sock_fd);
  822. }
  823.  
  824.  
  825. #ifndef NO_DUP
  826. /* s.dup() method */
  827.  
  828. static PyObject *
  829. BUILD_FUNC_DEF_2(PySocketSock_dup,PySocketSockObject *,s, PyObject *,args)
  830. {
  831.     int newfd;
  832.     PyObject *sock;
  833.     if (!PyArg_NoArgs(args))
  834.         return NULL;
  835.     newfd = dup(s->sock_fd);
  836.     if (newfd < 0)
  837.         return PySocket_Err();
  838.     sock = (PyObject *) PySocketSock_New(newfd,
  839.                          s->sock_family,
  840.                          s->sock_type,
  841.                          s->sock_proto);
  842.     if (sock == NULL)
  843.         close(newfd);
  844.     return sock;
  845. }
  846. #endif
  847.  
  848.  
  849. /* s.getsockname() method */
  850.  
  851. static PyObject *
  852. BUILD_FUNC_DEF_2(PySocketSock_getsockname,PySocketSockObject *,s, PyObject *,args)
  853. {
  854.     char addrbuf[256];
  855.     int addrlen, res;
  856.     if (!PyArg_NoArgs(args))
  857.         return NULL;
  858.     if (!getsockaddrlen(s, &addrlen))
  859.         return NULL;
  860.     memset(addrbuf, 0, addrlen);
  861.     Py_BEGIN_ALLOW_THREADS
  862.     res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  863.     Py_END_ALLOW_THREADS
  864.     if (res < 0)
  865.         return PySocket_Err();
  866.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  867. }
  868.  
  869.  
  870. #ifdef HAVE_GETPEERNAME        /* Cray APP doesn't have this :-( */
  871. /* s.getpeername() method */
  872.  
  873. static PyObject *
  874. BUILD_FUNC_DEF_2(PySocketSock_getpeername,PySocketSockObject *,s, PyObject *,args)
  875. {
  876.     char addrbuf[256];
  877.     int addrlen, res;
  878.     if (!PyArg_NoArgs(args))
  879.         return NULL;
  880.     if (!getsockaddrlen(s, &addrlen))
  881.         return NULL;
  882.     Py_BEGIN_ALLOW_THREADS
  883.     res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  884.     Py_END_ALLOW_THREADS
  885.     if (res < 0)
  886.         return PySocket_Err();
  887.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  888. }
  889. #endif /* HAVE_GETPEERNAME */
  890.  
  891.  
  892. /* s.listen(n) method */
  893.  
  894. static PyObject *
  895. BUILD_FUNC_DEF_2(PySocketSock_listen,PySocketSockObject *,s, PyObject *,args)
  896. {
  897.     int backlog;
  898.     int res;
  899.     if (!PyArg_Parse(args, "i", &backlog))
  900.         return NULL;
  901.     Py_BEGIN_ALLOW_THREADS
  902.     if (backlog < 1)
  903.         backlog = 1;
  904.     res = listen(s->sock_fd, backlog);
  905.     Py_END_ALLOW_THREADS
  906.     if (res < 0)
  907.         return PySocket_Err();
  908.     Py_INCREF(Py_None);
  909.     return Py_None;
  910. }
  911.  
  912. #ifndef NO_DUP
  913. /* s.makefile(mode) method.
  914.    Create a new open file object referring to a dupped version of
  915.    the socket's file descriptor.  (The dup() call is necessary so
  916.    that the open file and socket objects may be closed independent
  917.    of each other.)
  918.    The mode argument specifies 'r' or 'w' passed to fdopen(). */
  919.  
  920. static PyObject *
  921. BUILD_FUNC_DEF_2(PySocketSock_makefile,PySocketSockObject *,s, PyObject *,args)
  922. {
  923.     extern int fclose Py_PROTO((FILE *));
  924.     char *mode = "r";
  925.     int bufsize = -1;
  926.     int fd;
  927.     FILE *fp;
  928.     PyObject *f;
  929.  
  930.     if (!PyArg_ParseTuple(args, "|si", &mode, &bufsize))
  931.         return NULL;
  932. #ifdef MS_WIN32
  933.    if ( ((fd =  _open_osfhandle( s->sock_fd, _O_BINARY )) < 0) ||
  934.         ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL)) {
  935. #else
  936.     if ((fd = dup(s->sock_fd)) < 0 ||
  937.         (fp = fdopen(fd, mode)) == NULL) {
  938. #endif
  939.         if (fd >= 0)
  940.             close(fd);
  941.         return PySocket_Err();
  942.     }
  943.     f = PyFile_FromFile(fp, "<socket>", mode, fclose);
  944.     if (f != NULL)
  945.         PyFile_SetBufSize(f, bufsize);
  946.     return f;
  947. }
  948. #endif /* NO_DUP */
  949.  
  950. /* s.recv(nbytes [,flags]) method */
  951.  
  952. static PyObject *
  953. BUILD_FUNC_DEF_2(PySocketSock_recv,PySocketSockObject *,s, PyObject *,args)
  954. {
  955.     int len, n, flags = 0;
  956.     PyObject *buf;
  957.     if (!PyArg_ParseTuple(args, "i|i", &len, &flags))
  958.         return NULL;
  959.     buf = PyString_FromStringAndSize((char *) 0, len);
  960.     if (buf == NULL)
  961.         return NULL;
  962.     Py_BEGIN_ALLOW_THREADS
  963.     n = recv(s->sock_fd, PyString_AsString(buf), len, flags);
  964.     Py_END_ALLOW_THREADS
  965.     if (n < 0) {
  966.         Py_DECREF(buf);
  967.         return PySocket_Err();
  968.     }
  969.     if (n != len && _PyString_Resize(&buf, n) < 0)
  970.         return NULL;
  971.     return buf;
  972. }
  973.  
  974.  
  975. /* s.recvfrom(nbytes [,flags]) method */
  976.  
  977. static PyObject *
  978. BUILD_FUNC_DEF_2(PySocketSock_recvfrom,PySocketSockObject *,s, PyObject *,args)
  979. {
  980.     char addrbuf[256];
  981.     PyObject *buf = NULL;
  982.     PyObject *addr = NULL;
  983.     PyObject *ret = NULL;
  984.  
  985.     int addrlen, len, n, flags = 0;
  986.     if (!PyArg_ParseTuple(args, "i|i", &len, &flags))
  987.         return NULL;
  988.     if (!getsockaddrlen(s, &addrlen))
  989.         return NULL;
  990.     buf = PyString_FromStringAndSize((char *) 0, len);
  991.     if (buf == NULL)
  992.         return NULL;
  993.     Py_BEGIN_ALLOW_THREADS
  994.     n = recvfrom(s->sock_fd, PyString_AsString(buf), len, flags,
  995. #ifndef MS_WINDOWS
  996. #if defined(PYOS_OS2)
  997.              (struct sockaddr *)addrbuf, &addrlen
  998. #else
  999.              (ANY *)addrbuf, &addrlen
  1000. #endif
  1001. #else
  1002.              (struct sockaddr *)addrbuf, &addrlen
  1003. #endif
  1004.              );
  1005.     Py_END_ALLOW_THREADS
  1006.     if (n < 0) {
  1007.         Py_DECREF(buf);
  1008.         return PySocket_Err();
  1009.     }
  1010.     if (n != len && _PyString_Resize(&buf, n) < 0)
  1011.         return NULL;
  1012.         
  1013.     if (!(addr = makesockaddr((struct sockaddr *)addrbuf, addrlen)))
  1014.         goto finally;
  1015.  
  1016.     ret = Py_BuildValue("OO", buf, addr);
  1017.   finally:
  1018.     Py_XDECREF(addr);
  1019.     Py_XDECREF(buf);
  1020.     return ret;
  1021. }
  1022.  
  1023.  
  1024. /* s.send(data [,flags]) method */
  1025.  
  1026. static PyObject *
  1027. BUILD_FUNC_DEF_2(PySocketSock_send,PySocketSockObject *,s, PyObject *,args)
  1028. {
  1029.     char *buf;
  1030.     int len, n, flags = 0;
  1031.     if (!PyArg_ParseTuple(args, "s#|i", &buf, &len, &flags))
  1032.         return NULL;
  1033.     Py_BEGIN_ALLOW_THREADS
  1034.     n = send(s->sock_fd, buf, len, flags);
  1035.     Py_END_ALLOW_THREADS
  1036.     if (n < 0)
  1037.         return PySocket_Err();
  1038.     return PyInt_FromLong((long)n);
  1039. }
  1040.  
  1041.  
  1042. /* s.sendto(data, [flags,] sockaddr) method */
  1043.  
  1044. static PyObject *
  1045. BUILD_FUNC_DEF_2(PySocketSock_sendto,PySocketSockObject *,s, PyObject *,args)
  1046. {
  1047.     PyObject *addro;
  1048.     char *buf;
  1049.     struct sockaddr *addr;
  1050.     int addrlen, len, n, flags;
  1051.     flags = 0;
  1052.     if (!PyArg_Parse(args, "(s#O)", &buf, &len, &addro)) {
  1053.         PyErr_Clear();
  1054.         if (!PyArg_Parse(args, "(s#iO)", &buf, &len, &flags, &addro))
  1055.             return NULL;
  1056.     }
  1057.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  1058.         return NULL;
  1059.     Py_BEGIN_ALLOW_THREADS
  1060.     n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
  1061.     Py_END_ALLOW_THREADS
  1062.     if (n < 0)
  1063.         return PySocket_Err();
  1064.     return PyInt_FromLong((long)n);
  1065. }
  1066.  
  1067.  
  1068. /* s.shutdown(how) method */
  1069.  
  1070. static PyObject *
  1071. BUILD_FUNC_DEF_2(PySocketSock_shutdown,PySocketSockObject *,s, PyObject *,args)
  1072. {
  1073.     int how;
  1074.     int res;
  1075.     if (!PyArg_Parse(args, "i", &how))
  1076.         return NULL;
  1077.     Py_BEGIN_ALLOW_THREADS
  1078.     res = shutdown(s->sock_fd, how);
  1079.     Py_END_ALLOW_THREADS
  1080.     if (res < 0)
  1081.         return PySocket_Err();
  1082.     Py_INCREF(Py_None);
  1083.     return Py_None;
  1084. }
  1085.  
  1086.  
  1087. /* List of methods for socket objects */
  1088.  
  1089. static PyMethodDef PySocketSock_methods[] = {
  1090.     {"accept",        (PyCFunction)PySocketSock_accept},
  1091.     {"setblocking",        (PyCFunction)PySocketSock_setblocking},
  1092.     {"setsockopt",        (PyCFunction)PySocketSock_setsockopt},
  1093.     {"getsockopt",        (PyCFunction)PySocketSock_getsockopt, 1},
  1094.     {"bind",        (PyCFunction)PySocketSock_bind},
  1095.     {"close",        (PyCFunction)PySocketSock_close},
  1096.     {"connect",        (PyCFunction)PySocketSock_connect},
  1097.     {"connect_ex",        (PyCFunction)PySocketSock_connect_ex},
  1098.     {"fileno",        (PyCFunction)PySocketSock_fileno},
  1099. #ifndef NO_DUP
  1100.     {"dup",            (PyCFunction)PySocketSock_dup},
  1101. #endif
  1102.     {"getsockname",        (PyCFunction)PySocketSock_getsockname},
  1103. #ifdef HAVE_GETPEERNAME
  1104.     {"getpeername",        (PyCFunction)PySocketSock_getpeername},
  1105. #endif
  1106.     {"listen",        (PyCFunction)PySocketSock_listen},
  1107. #ifndef NO_DUP
  1108.     {"makefile",        (PyCFunction)PySocketSock_makefile, 1},
  1109. #endif
  1110.     {"recv",        (PyCFunction)PySocketSock_recv, 1},
  1111.     {"recvfrom",        (PyCFunction)PySocketSock_recvfrom, 1},
  1112.     {"send",        (PyCFunction)PySocketSock_send, 1},
  1113.     {"sendto",        (PyCFunction)PySocketSock_sendto},
  1114.     {"shutdown",        (PyCFunction)PySocketSock_shutdown},
  1115.     {NULL,            NULL}        /* sentinel */
  1116. };
  1117.  
  1118.  
  1119. /* Deallocate a socket object in response to the last Py_DECREF().
  1120.    First close the file description. */
  1121.  
  1122. static void
  1123. BUILD_FUNC_DEF_1(PySocketSock_dealloc,PySocketSockObject *,s)
  1124. {
  1125.     (void) close(s->sock_fd);
  1126.     PyMem_DEL(s);
  1127. }
  1128.  
  1129.  
  1130. /* Return a socket object's named attribute. */
  1131.  
  1132. static PyObject *
  1133. BUILD_FUNC_DEF_2(PySocketSock_getattr,PySocketSockObject *,s, char *,name)
  1134. {
  1135.     return Py_FindMethod(PySocketSock_methods, (PyObject *) s, name);
  1136. }
  1137.  
  1138.  
  1139. static PyObject *
  1140. BUILD_FUNC_DEF_1(PySocketSock_repr,PySocketSockObject *,s)
  1141. {
  1142.     char buf[512];
  1143.     sprintf(buf, 
  1144.         "<socket object, fd=%d, family=%d, type=%d, protocol=%d>", 
  1145.         s->sock_fd, s->sock_family, s->sock_type, s->sock_proto);
  1146.     return PyString_FromString(buf);
  1147. }
  1148.  
  1149.  
  1150. /* Type object for socket objects. */
  1151.  
  1152. static PyTypeObject PySocketSock_Type = {
  1153.     PyObject_HEAD_INIT(0)    /* Must fill in type value later */
  1154.     0,
  1155.     "socket",
  1156.     sizeof(PySocketSockObject),
  1157.     0,
  1158.     (destructor)PySocketSock_dealloc, /*tp_dealloc*/
  1159.     0,        /*tp_print*/
  1160.     (getattrfunc)PySocketSock_getattr, /*tp_getattr*/
  1161.     0,        /*tp_setattr*/
  1162.     0,        /*tp_compare*/
  1163.     (reprfunc)PySocketSock_repr, /*tp_repr*/
  1164.     0,        /*tp_as_number*/
  1165.     0,        /*tp_as_sequence*/
  1166.     0,        /*tp_as_mapping*/
  1167. };
  1168.  
  1169.  
  1170. /* Python interface to gethostname(). */
  1171.  
  1172. /*ARGSUSED*/
  1173. static PyObject *
  1174. BUILD_FUNC_DEF_2(PySocket_gethostname,PyObject *,self, PyObject *,args)
  1175. {
  1176.     char buf[1024];
  1177.     int res;
  1178.     if (!PyArg_NoArgs(args))
  1179.         return NULL;
  1180.     Py_BEGIN_ALLOW_THREADS
  1181.     res = gethostname(buf, (int) sizeof buf - 1);
  1182.     Py_END_ALLOW_THREADS
  1183.     if (res < 0)
  1184.         return PySocket_Err();
  1185.     buf[sizeof buf - 1] = '\0';
  1186.     return PyString_FromString(buf);
  1187. }
  1188.  
  1189.  
  1190. /* Python interface to gethostbyname(name). */
  1191.  
  1192. /*ARGSUSED*/
  1193. static PyObject *
  1194. BUILD_FUNC_DEF_2(PySocket_gethostbyname,PyObject *,self, PyObject *,args)
  1195. {
  1196.     char *name;
  1197.     struct sockaddr_in addrbuf;
  1198.     if (!PyArg_Parse(args, "s", &name))
  1199.         return NULL;
  1200.     if (setipaddr(name, &addrbuf) < 0)
  1201.         return NULL;
  1202.     return makeipaddr(&addrbuf);
  1203. }
  1204.  
  1205. /* Python interface to gethostbyaddr(IP). */
  1206.  
  1207. /*ARGSUSED*/
  1208. static PyObject *
  1209. BUILD_FUNC_DEF_2(PySocket_gethostbyaddr,PyObject *,self, PyObject *, args)
  1210. {
  1211.         struct sockaddr_in addr;
  1212.     char *ip_num;
  1213.     struct hostent *h;
  1214.     char **pch;
  1215.     PyObject *rtn_tuple = (PyObject *)NULL;
  1216.     PyObject *name_list = (PyObject *)NULL;
  1217.     PyObject *addr_list = (PyObject *)NULL;
  1218.     PyObject *tmp;
  1219. #ifdef HAVE_GETHOSTBYNAME_R
  1220.     struct hostent hp_allocated;
  1221.     char buf[16384];
  1222.     int buf_len = (sizeof buf) - 1;
  1223.     int errnop;
  1224. #endif /* HAVE_GETHOSTBYNAME_R */
  1225.  
  1226.     if (!PyArg_Parse(args, "s", &ip_num))
  1227.         return NULL;
  1228.     if (setipaddr(ip_num, &addr) < 0)
  1229.         return NULL;
  1230.     Py_BEGIN_ALLOW_THREADS
  1231. #ifdef HAVE_GETHOSTBYNAME_R
  1232.     h = gethostbyaddr_r((char *)&addr.sin_addr,
  1233.                 sizeof(addr.sin_addr),
  1234.                 AF_INET, 
  1235.                 &hp_allocated, buf, buf_len, &errnop);
  1236. #else /* not HAVE_GETHOSTBYNAME_R */
  1237. #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
  1238.     acquire_lock(gethostbyname_lock,1);
  1239. #endif
  1240.     h = gethostbyaddr((char *)&addr.sin_addr,
  1241.               sizeof(addr.sin_addr),
  1242.               AF_INET);
  1243. #if defined(WITH_THREAD) && !defined(MS_WINDOWS)
  1244.     release_lock(gethostbyname_lock);
  1245. #endif
  1246. #endif /* HAVE_GETHOSTBYNAME_R */
  1247.     Py_END_ALLOW_THREADS
  1248.     if (h == NULL) {
  1249. #ifdef HAVE_HSTRERROR
  1250.             /* Let's get real error message to return */
  1251.             extern int h_errno;
  1252.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  1253. #else
  1254.         PyErr_SetString(PySocket_Error, "host not found");
  1255. #endif
  1256.         return NULL;
  1257.     }
  1258.     if ((name_list = PyList_New(0)) == NULL)
  1259.         goto err;
  1260.     if ((addr_list = PyList_New(0)) == NULL)
  1261.         goto err;
  1262.     for (pch = h->h_aliases; *pch != NULL; pch++) {
  1263.         int status;
  1264.         tmp = PyString_FromString(*pch);
  1265.         if (tmp == NULL)
  1266.             goto err;
  1267.         status = PyList_Append(name_list, tmp);
  1268.         Py_DECREF(tmp);
  1269.         if (status)
  1270.             goto err;
  1271.     }
  1272.     for (pch = h->h_addr_list; *pch != NULL; pch++) {
  1273.         int status;
  1274.         memcpy((char *) &addr.sin_addr, *pch, h->h_length);
  1275.         tmp = makeipaddr(&addr);
  1276.         if (tmp == NULL)
  1277.             goto err;
  1278.         status = PyList_Append(addr_list, tmp);
  1279.         Py_DECREF(tmp);
  1280.         if (status)
  1281.             goto err;
  1282.     }
  1283.     rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
  1284.  err:
  1285.     Py_XDECREF(name_list);
  1286.     Py_XDECREF(addr_list);
  1287.     return rtn_tuple;
  1288. }
  1289.  
  1290.  
  1291. /* Python interface to getservbyname(name).
  1292.    This only returns the port number, since the other info is already
  1293.    known or not useful (like the list of aliases). */
  1294.  
  1295. /*ARGSUSED*/
  1296. static PyObject *
  1297. BUILD_FUNC_DEF_2(PySocket_getservbyname,PyObject *,self, PyObject *,args)
  1298. {
  1299.     char *name, *proto;
  1300.     struct servent *sp;
  1301.     if (!PyArg_Parse(args, "(ss)", &name, &proto))
  1302.         return NULL;
  1303.     Py_BEGIN_ALLOW_THREADS
  1304.     sp = getservbyname(name, proto);
  1305.     Py_END_ALLOW_THREADS
  1306.     if (sp == NULL) {
  1307.         PyErr_SetString(PySocket_Error, "service/proto not found");
  1308.         return NULL;
  1309.     }
  1310.     return PyInt_FromLong((long) ntohs(sp->s_port));
  1311. }
  1312.  
  1313.  
  1314. /* Python interface to getprotobyname(name).
  1315.    This only returns the protocol number, since the other info is
  1316.    already known or not useful (like the list of aliases). */
  1317.  
  1318. /*ARGSUSED*/
  1319. static PyObject *
  1320. BUILD_FUNC_DEF_2(PySocket_getprotobyname,PyObject *,self, PyObject *,args)
  1321. {
  1322.     char *name;
  1323.     struct protoent *sp;
  1324.     if (!PyArg_Parse(args, "s", &name))
  1325.         return NULL;
  1326.     Py_BEGIN_ALLOW_THREADS
  1327.     sp = getprotobyname(name);
  1328.     Py_END_ALLOW_THREADS
  1329.     if (sp == NULL) {
  1330.         PyErr_SetString(PySocket_Error, "protocol not found");
  1331.         return NULL;
  1332.     }
  1333.     return PyInt_FromLong((long) sp->p_proto);
  1334. }
  1335.  
  1336.  
  1337. /* Python interface to socket(family, type, proto).
  1338.    The third (protocol) argument is optional.
  1339.    Return a new socket object. */
  1340.  
  1341. /*ARGSUSED*/
  1342. static PyObject *
  1343. BUILD_FUNC_DEF_2(PySocket_socket,PyObject *,self, PyObject *,args)
  1344. {
  1345.     PySocketSockObject *s;
  1346. #ifdef MS_WINDOWS
  1347.     SOCKET fd;
  1348. #else
  1349.     int fd;
  1350. #endif
  1351.     int family, type, proto = 0;
  1352.     if (!PyArg_ParseTuple(args, "ii|i", &family, &type, &proto))
  1353.         return NULL;
  1354.     Py_BEGIN_ALLOW_THREADS
  1355.     fd = socket(family, type, proto);
  1356.     Py_END_ALLOW_THREADS
  1357. #ifdef MS_WINDOWS
  1358.     if (fd == INVALID_SOCKET)
  1359. #else
  1360.     if (fd < 0)
  1361. #endif
  1362.         return PySocket_Err();
  1363.     s = PySocketSock_New(fd, family, type, proto);
  1364.     /* If the object can't be created, don't forget to close the
  1365.        file descriptor again! */
  1366.     if (s == NULL)
  1367.         (void) close(fd);
  1368.     /* From now on, ignore SIGPIPE and let the error checking
  1369.        do the work. */
  1370. #ifdef SIGPIPE      
  1371.     (void) signal(SIGPIPE, SIG_IGN);
  1372. #endif   
  1373.     return (PyObject *) s;
  1374. }
  1375.  
  1376. #ifndef NO_DUP
  1377. /* Create a socket object from a numeric file description.
  1378.    Useful e.g. if stdin is a socket.
  1379.    Additional arguments as for socket(). */
  1380.  
  1381. /*ARGSUSED*/
  1382. static PyObject *
  1383. BUILD_FUNC_DEF_2(PySocket_fromfd,PyObject *,self, PyObject *,args)
  1384. {
  1385.     PySocketSockObject *s;
  1386.     int fd, family, type, proto = 0;
  1387.     if (!PyArg_ParseTuple(args, "iii|i", &fd, &family, &type, &proto))
  1388.         return NULL;
  1389.     /* Dup the fd so it and the socket can be closed independently */
  1390.     fd = dup(fd);
  1391.     if (fd < 0)
  1392.         return PySocket_Err();
  1393.     s = PySocketSock_New(fd, family, type, proto);
  1394.     /* From now on, ignore SIGPIPE and let the error checking
  1395.        do the work. */
  1396. #ifdef SIGPIPE      
  1397.     (void) signal(SIGPIPE, SIG_IGN);
  1398. #endif   
  1399.     return (PyObject *) s;
  1400. }
  1401. #endif /* NO_DUP */
  1402.  
  1403. static PyObject *
  1404. BUILD_FUNC_DEF_2(PySocket_ntohs, PyObject *, self, PyObject *, args)
  1405. {
  1406.     int x1, x2;
  1407.  
  1408.     if (!PyArg_Parse(args, "i", &x1)) {
  1409.         return NULL;
  1410.     }
  1411.     x2 = (int)ntohs((short)x1);
  1412.     return PyInt_FromLong(x2);
  1413. }
  1414.  
  1415. static PyObject *
  1416. BUILD_FUNC_DEF_2(PySocket_ntohl, PyObject *, self, PyObject *, args)
  1417. {
  1418.     int x1, x2;
  1419.  
  1420.     if (!PyArg_Parse(args, "i", &x1)) {
  1421.         return NULL;
  1422.     }
  1423.     x2 = ntohl(x1);
  1424.     return PyInt_FromLong(x2);
  1425. }
  1426.  
  1427. static PyObject *
  1428. BUILD_FUNC_DEF_2(PySocket_htons, PyObject *, self, PyObject *, args)
  1429. {
  1430.     int x1, x2;
  1431.  
  1432.     if (!PyArg_Parse(args, "i", &x1)) {
  1433.         return NULL;
  1434.     }
  1435.     x2 = (int)htons((short)x1);
  1436.     return PyInt_FromLong(x2);
  1437. }
  1438.  
  1439. static PyObject *
  1440. BUILD_FUNC_DEF_2(PySocket_htonl, PyObject *, self, PyObject *, args)
  1441. {
  1442.     int x1, x2;
  1443.  
  1444.     if (!PyArg_Parse(args, "i", &x1)) {
  1445.         return NULL;
  1446.     }
  1447.     x2 = htonl(x1);
  1448.     return PyInt_FromLong(x2);
  1449. }
  1450.  
  1451. /* List of functions exported by this module. */
  1452.  
  1453. static PyMethodDef PySocket_methods[] = {
  1454.     {"gethostbyname",    PySocket_gethostbyname},
  1455.     {"gethostbyaddr",    PySocket_gethostbyaddr},
  1456.     {"gethostname",        PySocket_gethostname},
  1457.     {"getservbyname",    PySocket_getservbyname},
  1458.     {"getprotobyname",    PySocket_getprotobyname},
  1459.     {"socket",        PySocket_socket, 1},
  1460. #ifndef NO_DUP
  1461.     {"fromfd",        PySocket_fromfd, 1},
  1462. #endif
  1463.     {"ntohs",        PySocket_ntohs},
  1464.     {"ntohl",        PySocket_ntohl},
  1465.     {"htons",        PySocket_htons},
  1466.     {"htonl",        PySocket_htonl},
  1467.     {NULL,            NULL}         /* Sentinel */
  1468. };
  1469.  
  1470.  
  1471. /* Convenience routine to export an integer value.
  1472.  *
  1473.  * Errors are silently ignored, for better or for worse...
  1474.  */
  1475. static void
  1476. BUILD_FUNC_DEF_3(insint,PyObject *,d, char *,name, int,value)
  1477. {
  1478.     PyObject *v = PyInt_FromLong((long) value);
  1479.     if (!v || PyDict_SetItemString(d, name, v))
  1480.         PyErr_Clear();
  1481.  
  1482.     Py_XDECREF(v);
  1483. }
  1484.  
  1485.  
  1486. #ifdef MS_WINDOWS
  1487.  
  1488. /* Additional initialization and cleanup for NT/Windows */
  1489.  
  1490. static void
  1491. NTcleanup()
  1492. {
  1493.     WSACleanup();
  1494. }
  1495.  
  1496. static int
  1497. NTinit()
  1498. {
  1499.     WSADATA WSAData;
  1500.     int ret;
  1501.     char buf[100];
  1502.     ret = WSAStartup(0x0101, &WSAData);
  1503.     switch (ret) {
  1504.     case 0:    /* no error */
  1505.         atexit(NTcleanup);
  1506.         return 1;
  1507.     case WSASYSNOTREADY:
  1508.         PyErr_SetString(PyExc_ImportError,
  1509.                 "WSAStartup failed: network not ready");
  1510.         break;
  1511.     case WSAVERNOTSUPPORTED:
  1512.     case WSAEINVAL:
  1513.         PyErr_SetString(PyExc_ImportError,
  1514.             "WSAStartup failed: requested version not supported");
  1515.         break;
  1516.     default:
  1517.         sprintf(buf, "WSAStartup failed: error code %d", ret);
  1518.         PyErr_SetString(PyExc_ImportError, buf);
  1519.         break;
  1520.     }
  1521.     return 0;
  1522. }
  1523.  
  1524. #endif /* MS_WINDOWS */
  1525.  
  1526. #if defined(PYOS_OS2)
  1527.  
  1528. /* Additional initialization and cleanup for OS/2 */
  1529.  
  1530. static void
  1531. OS2cleanup()
  1532. {
  1533.     /* No cleanup is necessary for OS/2 Sockets */
  1534. }
  1535.  
  1536. static int
  1537. OS2init()
  1538. {
  1539.     char reason[64];
  1540.     int rc = sock_init();
  1541.  
  1542.     if (rc == 0) {
  1543.         atexit(OS2cleanup);
  1544.         return 1; /* Indicate Success */
  1545.     }
  1546.  
  1547.     sprintf(reason, "OS/2 TCP/IP Error# %d", sock_errno());
  1548.     PyErr_SetString(PyExc_ImportError, reason);
  1549.  
  1550.     return 0;  /* Indicate Failure */
  1551. }
  1552.  
  1553. #endif /* PYOS_OS2 */
  1554.  
  1555.  
  1556. /* Initialize this module.
  1557.  *   This is called when the first 'import socket' is done,
  1558.  *   via a table in config.c, if config.c is compiled with USE_SOCKET
  1559.  *   defined.
  1560.  *
  1561.  *   For MS_WINDOWS (which means any Windows variant), this module
  1562.  *   is actually called "_socket", and there's a wrapper "socket.py"
  1563.  *   which implements some missing functionality (such as makefile(),
  1564.  *   dup() and fromfd()).  The import of "_socket" may fail with an
  1565.  *   ImportError exception if initialization of WINSOCK fails.  When
  1566.  *   WINSOCK is initialized succesfully, a call to WSACleanup() is
  1567.  *   scheduled to be made at exit time.
  1568.  *
  1569.  *   For OS/2, this module is also called "_socket" and uses a wrapper
  1570.  *   "socket.py" which implements that functionality that is missing
  1571.  *   when PC operating systems don't put socket descriptors in the
  1572.  *   operating system's filesystem layer.
  1573.  */
  1574.  
  1575. void
  1576. #if defined(MS_WINDOWS) || defined(PYOS_OS2)
  1577. init_socket()
  1578. #else
  1579. initsocket()
  1580. #endif
  1581. {
  1582.     PyObject *m, *d;
  1583. #if defined(AMITCP) || defined(INET225)
  1584.     if(!checksocketlib()) return;
  1585. #endif
  1586. #ifdef MS_WINDOWS
  1587.     if (!NTinit())
  1588.         return;
  1589.     m = Py_InitModule("_socket", PySocket_methods);
  1590. #else
  1591. #if defined(__TOS_OS2__)
  1592.     if (!OS2init())
  1593.         return;
  1594.     m = Py_InitModule("_socket", PySocket_methods);
  1595. #else
  1596.     m = Py_InitModule("socket", PySocket_methods);
  1597. #endif
  1598. #endif
  1599.     d = PyModule_GetDict(m);
  1600.     PySocket_Error = PyErr_NewException("socket.error", NULL, NULL);
  1601.     if (PySocket_Error == NULL)
  1602.         return;
  1603.     PyDict_SetItemString(d, "error", PySocket_Error);
  1604.     PySocketSock_Type.ob_type = &PyType_Type;
  1605.     Py_INCREF(&PySocketSock_Type);
  1606.     if (PyDict_SetItemString(d, "SocketType",
  1607.                  (PyObject *)&PySocketSock_Type) != 0)
  1608.         return;
  1609.     insint(d, "AF_INET", AF_INET);
  1610. #ifdef AF_UNIX
  1611.     insint(d, "AF_UNIX", AF_UNIX);
  1612. #endif /* AF_UNIX */
  1613.     insint(d, "SOCK_STREAM", SOCK_STREAM);
  1614.     insint(d, "SOCK_DGRAM", SOCK_DGRAM);
  1615.     insint(d, "SOCK_RAW", SOCK_RAW);
  1616.     insint(d, "SOCK_SEQPACKET", SOCK_SEQPACKET);
  1617.     insint(d, "SOCK_RDM", SOCK_RDM);
  1618.  
  1619. #ifdef    SO_DEBUG
  1620.     insint(d, "SO_DEBUG", SO_DEBUG);
  1621. #endif
  1622. #ifdef    SO_ACCEPTCONN
  1623.     insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN);
  1624. #endif
  1625. #ifdef    SO_REUSEADDR
  1626.     insint(d, "SO_REUSEADDR", SO_REUSEADDR);
  1627. #endif
  1628. #ifdef    SO_KEEPALIVE
  1629.     insint(d, "SO_KEEPALIVE", SO_KEEPALIVE);
  1630. #endif
  1631. #ifdef    SO_DONTROUTE
  1632.     insint(d, "SO_DONTROUTE", SO_DONTROUTE);
  1633. #endif
  1634. #ifdef    SO_BROADCAST
  1635.     insint(d, "SO_BROADCAST", SO_BROADCAST);
  1636. #endif
  1637. #ifdef    SO_USELOOPBACK
  1638.     insint(d, "SO_USELOOPBACK", SO_USELOOPBACK);
  1639. #endif
  1640. #ifdef    SO_LINGER
  1641.     insint(d, "SO_LINGER", SO_LINGER);
  1642. #endif
  1643. #ifdef    SO_OOBINLINE
  1644.     insint(d, "SO_OOBINLINE", SO_OOBINLINE);
  1645. #endif
  1646. #ifdef    SO_REUSEPORT
  1647.     insint(d, "SO_REUSEPORT", SO_REUSEPORT);
  1648. #endif
  1649.  
  1650. #ifdef    SO_SNDBUF
  1651.     insint(d, "SO_SNDBUF", SO_SNDBUF);
  1652. #endif
  1653. #ifdef    SO_RCVBUF
  1654.     insint(d, "SO_RCVBUF", SO_RCVBUF);
  1655. #endif
  1656. #ifdef    SO_SNDLOWAT
  1657.     insint(d, "SO_SNDLOWAT", SO_SNDLOWAT);
  1658. #endif
  1659. #ifdef    SO_RCVLOWAT
  1660.     insint(d, "SO_RCVLOWAT", SO_RCVLOWAT);
  1661. #endif
  1662. #ifdef    SO_SNDTIMEO
  1663.     insint(d, "SO_SNDTIMEO", SO_SNDTIMEO);
  1664. #endif
  1665. #ifdef    SO_RCVTIMEO
  1666.     insint(d, "SO_RCVTIMEO", SO_RCVTIMEO);
  1667. #endif
  1668. #ifdef    SO_ERROR
  1669.     insint(d, "SO_ERROR", SO_ERROR);
  1670. #endif
  1671. #ifdef    SO_TYPE
  1672.     insint(d, "SO_TYPE", SO_TYPE);
  1673. #endif
  1674.  
  1675.     /* Maximum number of connections for "listen" */
  1676. #ifdef    SOMAXCONN
  1677.     insint(d, "SOMAXCONN", SOMAXCONN);
  1678. #else
  1679.     insint(d, "SOMAXCONN", 5);    /* Common value */
  1680. #endif
  1681.  
  1682.     /* Flags for send, recv */
  1683. #ifdef    MSG_OOB
  1684.     insint(d, "MSG_OOB", MSG_OOB);
  1685. #endif
  1686. #ifdef    MSG_PEEK
  1687.     insint(d, "MSG_PEEK", MSG_PEEK);
  1688. #endif
  1689. #ifdef    MSG_DONTROUTE
  1690.     insint(d, "MSG_DONTROUTE", MSG_DONTROUTE);
  1691. #endif
  1692. #ifdef    MSG_EOR
  1693.     insint(d, "MSG_EOR", MSG_EOR);
  1694. #endif
  1695. #ifdef    MSG_TRUNC
  1696.     insint(d, "MSG_TRUNC", MSG_TRUNC);
  1697. #endif
  1698. #ifdef    MSG_CTRUNC
  1699.     insint(d, "MSG_CTRUNC", MSG_CTRUNC);
  1700. #endif
  1701. #ifdef    MSG_WAITALL
  1702.     insint(d, "MSG_WAITALL", MSG_WAITALL);
  1703. #endif
  1704. #ifdef    MSG_BTAG
  1705.     insint(d, "MSG_BTAG", MSG_BTAG);
  1706. #endif
  1707. #ifdef    MSG_ETAG
  1708.     insint(d, "MSG_ETAG", MSG_ETAG);
  1709. #endif
  1710.  
  1711.     /* Protocol level and numbers, usable for [gs]etsockopt */
  1712. #ifdef    SOL_SOCKET
  1713.     insint(d, "SOL_SOCKET", SOL_SOCKET);
  1714. #endif
  1715. #ifdef    IPPROTO_IP
  1716.     insint(d, "IPPROTO_IP", IPPROTO_IP);
  1717. #endif
  1718. #ifdef    IPPROTO_ICMP
  1719.     insint(d, "IPPROTO_ICMP", IPPROTO_ICMP);
  1720. #endif
  1721. #ifdef    IPPROTO_IGMP
  1722.     insint(d, "IPPROTO_IGMP", IPPROTO_IGMP);
  1723. #endif
  1724. #ifdef    IPPROTO_GGP
  1725.     insint(d, "IPPROTO_GGP", IPPROTO_GGP);
  1726. #endif
  1727. #ifdef    IPPROTO_TCP
  1728.     insint(d, "IPPROTO_TCP", IPPROTO_TCP);
  1729. #endif
  1730. #ifdef    IPPROTO_EGP
  1731.     insint(d, "IPPROTO_EGP", IPPROTO_EGP);
  1732. #endif
  1733. #ifdef    IPPROTO_PUP
  1734.     insint(d, "IPPROTO_PUP", IPPROTO_PUP);
  1735. #endif
  1736. #ifdef    IPPROTO_UDP
  1737.     insint(d, "IPPROTO_UDP", IPPROTO_UDP);
  1738. #endif
  1739. #ifdef    IPPROTO_IDP
  1740.     insint(d, "IPPROTO_IDP", IPPROTO_IDP);
  1741. #endif
  1742. #ifdef    IPPROTO_HELLO
  1743.     insint(d, "IPPROTO_HELLO", IPPROTO_HELLO);
  1744. #endif
  1745. #ifdef    IPPROTO_ND
  1746.     insint(d, "IPPROTO_ND", IPPROTO_ND);
  1747. #endif
  1748. #ifdef    IPPROTO_TP
  1749.     insint(d, "IPPROTO_TP", IPPROTO_TP);
  1750. #endif
  1751. #ifdef    IPPROTO_XTP
  1752.     insint(d, "IPPROTO_XTP", IPPROTO_XTP);
  1753. #endif
  1754. #ifdef    IPPROTO_EON
  1755.     insint(d, "IPPROTO_EON", IPPROTO_EON);
  1756. #endif
  1757. #ifdef    IPPROTO_BIP
  1758.     insint(d, "IPPROTO_BIP", IPPROTO_BIP);
  1759. #endif
  1760. /**/
  1761. #ifdef    IPPROTO_RAW
  1762.     insint(d, "IPPROTO_RAW", IPPROTO_RAW);
  1763. #endif
  1764. #ifdef    IPPROTO_MAX
  1765.     insint(d, "IPPROTO_MAX", IPPROTO_MAX);
  1766. #endif
  1767.  
  1768.     /* Some port configuration */
  1769. #ifdef    IPPORT_RESERVED
  1770.     insint(d, "IPPORT_RESERVED", IPPORT_RESERVED);
  1771. #else
  1772.     insint(d, "IPPORT_RESERVED", 1024);
  1773. #endif
  1774. #ifdef    IPPORT_USERRESERVED
  1775.     insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
  1776. #else
  1777.     insint(d, "IPPORT_USERRESERVED", 5000);
  1778. #endif
  1779.  
  1780.     /* Some reserved IP v.4 addresses */
  1781. #ifdef    INADDR_ANY
  1782.     insint(d, "INADDR_ANY", INADDR_ANY);
  1783. #else
  1784.     insint(d, "INADDR_ANY", 0x00000000);
  1785. #endif
  1786. #ifdef    INADDR_BROADCAST
  1787.     insint(d, "INADDR_BROADCAST", INADDR_BROADCAST);
  1788. #else
  1789.     insint(d, "INADDR_BROADCAST", 0xffffffff);
  1790. #endif
  1791. #ifdef    INADDR_LOOPBACK
  1792.     insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK);
  1793. #else
  1794.     insint(d, "INADDR_LOOPBACK", 0x7F000001);
  1795. #endif
  1796. #ifdef    INADDR_UNSPEC_GROUP
  1797.     insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
  1798. #else
  1799.     insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000);
  1800. #endif
  1801. #ifdef    INADDR_ALLHOSTS_GROUP
  1802.     insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
  1803. #else
  1804.     insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
  1805. #endif
  1806. #ifdef    INADDR_MAX_LOCAL_GROUP
  1807.     insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
  1808. #else
  1809.     insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
  1810. #endif
  1811. #ifdef    INADDR_NONE
  1812.     insint(d, "INADDR_NONE", INADDR_NONE);
  1813. #else
  1814.     insint(d, "INADDR_NONE", 0xffffffff);
  1815. #endif
  1816.  
  1817.     /* IP [gs]etsockopt options */
  1818. #ifdef    IP_OPTIONS
  1819.     insint(d, "IP_OPTIONS", IP_OPTIONS);
  1820. #endif
  1821. #ifdef    IP_HDRINCL
  1822.     insint(d, "IP_HDRINCL", IP_HDRINCL);
  1823. #endif
  1824. #ifdef    IP_TOS
  1825.     insint(d, "IP_TOS", IP_TOS);
  1826. #endif
  1827. #ifdef    IP_TTL
  1828.     insint(d, "IP_TTL", IP_TTL);
  1829. #endif
  1830. #ifdef    IP_RECVOPTS
  1831.     insint(d, "IP_RECVOPTS", IP_RECVOPTS);
  1832. #endif
  1833. #ifdef    IP_RECVRETOPTS
  1834.     insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS);
  1835. #endif
  1836. #ifdef    IP_RECVDSTADDR
  1837.     insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR);
  1838. #endif
  1839. #ifdef    IP_RETOPTS
  1840.     insint(d, "IP_RETOPTS", IP_RETOPTS);
  1841. #endif
  1842. #ifdef    IP_MULTICAST_IF
  1843.     insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF);
  1844. #endif
  1845. #ifdef    IP_MULTICAST_TTL
  1846.     insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
  1847. #endif
  1848. #ifdef    IP_MULTICAST_LOOP
  1849.     insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
  1850. #endif
  1851. #ifdef    IP_ADD_MEMBERSHIP
  1852.     insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
  1853. #endif
  1854. #ifdef    IP_DROP_MEMBERSHIP
  1855.     insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
  1856. #endif
  1857.  
  1858.     /* Initialize gethostbyname lock */
  1859. #if defined(WITH_THREAD) && !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
  1860.     gethostbyname_lock = allocate_lock();
  1861. #endif
  1862. }
  1863.